package Util;

import java.sql.*;

public class javautil1 {
        private static String driver = ("com.mysql.jdbc.Driver");
        private static String url = "jdbc:mysql://localhost:3306/library?useSSL=false&useUnicode=true&characterEncoding=utf-8";
        private static String username = "root";
        private static String password = "root";

        private static Connection con;
        private static PreparedStatement ps;
        private static ResultSet rs;

        //    获取链接
        public static boolean getCon() {
//        Connection con = null;
            try {
                Class.forName(driver);
                con = DriverManager.getConnection(url, username, password);
            } catch (ClassNotFoundException | SQLException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }

        //增删改
        public static int excuteupdate(String sql, Object[] params) {
            int updaterows = 0;
            if (getCon() == true) {
                try {
                    ps = con.prepareStatement(sql);
                    for (int i = 0; i < params.length; i++) {
                        ps.setObject(i + 1, params[i]);
                    }
                    updaterows = ps.executeUpdate();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            return updaterows;
        }

        //    查询
        public static ResultSet excutquery(String sql, Object[] params) {
            if (getCon()) {
                try {
                    ps = con.prepareStatement(sql);
                    for (int i = 0; i < params.length; i++) {
                        ps.setObject(i + 1, params[i]);
                    }
                    rs = ps.executeQuery();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            return rs;
        }

        //关闭链接
        public static void close() {
            if (rs != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                if (ps != null) {
                    try {
                        ps.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    if (con != null) {
                        try {
                            con.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

